import Header from "../../components/Header/Header.tsx";
import {Button, Card, Form, Input, InputNumber, message, Switch, Upload} from "antd";
import ImgCrop from "antd-img-crop";
import {UploadOutlined} from "@ant-design/icons";
import {useDispatch, useSelector} from "react-redux";
import {RootState} from "../../store";
import {useEffect, useState} from "react";
import {useNavigate} from "react-router-dom";
import "./index.css";
import {getUserInfoUsingGet} from "../../api/userController.ts";
import {addFriendUsingPost} from "../../api/friendController.ts";
import {addRoomUsingPost} from "../../api/roomController.ts";

const AddRoom = () => {
  let userInfo = useSelector((state: RootState) => state.loginUser);
  const [fileList, setFileList] = useState([]);
  const [passwordFlag,setPasswordFlag] = useState(true);
  const [form] = Form.useForm(); // 使用 Form 实例来获取表单数据
  const navigate = useNavigate();
  const dispatch = useDispatch();

  useEffect(() => {
    if (userInfo.avatarUrl) {
      // 初始化头像
      setFileList([]);
    }
  }, [userInfo.avatarUrl]);

  // 处理上传变更
  const onChange = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  };

  // 处理上传前的验证
  const beforeUpload = (file) => {
    // 限制上传的文件类型为图片
    const isImage = file.type.startsWith("image/");
    if (!isImage) {
      message.error("请上传图片文件！");
    }
    return isImage;
  };

  // 获取 session 信息（例如从 localStorage 或 cookies 中）
  const getSessionInfo = () => {
    return (
      "Webstorm-80cf4c34=e56559b8-7647-46e3-a37e-52745903d4cf; xinggui-init-token=" +
        document.cookie
          .split("; ")
          .find((cookie) => cookie.startsWith("xinggui-init-token="))
          ?.split("=")[1] || ""
    );
  };

  //获取Switch值
  const onFinish = async (values) => {
    try {
      if (fileList.length < 1) {
        return message.error("上传图片为空");
      }
      const res = await addRoomUsingPost({
        ...values,
        room_cover: fileList[0].url, // 使用最新的头像 URL
      });
      if (res.code == 200) {
        message.success("添加房间成功");
        await getUserInfoUsingGet();
        navigate("/home", { replace: true });
      }
    } catch (e) {
      message.error(e.message);
    }
  };

  return (
    <div>
      <Header></Header>
      <div>
        <div style={{ maxWidth: 1400 }} className={"m-auto mb-2 pl-2 pr-2"}>
          <Card title={"创建房间"} className={"shadow"}>
            <Form
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 18 }} // 设置 wrapperCol 为 20，确保表单项内容占满大部分空间
              layout="horizontal"
              style={{ width: "100%" }}
              onFinish={onFinish}
              form={form} // 绑定 form 实例
            >
              <Form.Item
                label="房间名称"
                name="roomName"
                rules={[
                  {
                    required: true,
                    min: 4,
                    max: 30,
                    message: "房间名称长度在4-30个字符之间",
                  },
                ]}
              >
                <Input placeholder="请输入房间名称" style={{ width: "100%" }} />
              </Form.Item>
              <Form.Item
                label="房间描述"
                name="roomProfile"
                rules={[
                  {
                    required: true,
                    min: 5,
                    message: "房间描述必须大于5个字",
                  },
                ]}
              >
                <Input.TextArea rows={3} placeholder="请输入房间描述" />
              </Form.Item>
              <Form.Item label="房间最大人数" name="maxPeople" required={true}>
                <InputNumber className={"w-[140px]"} min={1} max={50} placeholder={"请输入房间人数"}  onChange={()=>{
                  console.log("123123")
                }} />
              </Form.Item>
              <Form.Item label="是否需要密码" name="isPassword" valuePropName="checked" initialValue={passwordFlag} required={true} >
                <Switch onChange={()=>{
                  setPasswordFlag(!passwordFlag)
                }} />
              </Form.Item>
              {
                passwordFlag && (
                      <Form.Item
                          label="房间密码"
                          name="roomPassword"
                          rules={[
                            {
                              required: true,
                              min: 6,
                              max: 6,
                              message: "房间密码必须是6位",
                            },
                          ]}
                      >
                        <Input placeholder="请输入您要设置的密码" style={{ width: "100%" }} />
                      </Form.Item>
                  )
              }
              <Form.Item
                label="用户头像"
                name={"room_cover"}
                valuePropName="fileList" // 绑定 `fileList`
              >
                <ImgCrop aspect={16 / 9} rotationSlider >
                  <Upload
                    action="http://localhost:8102/api/file/upload" // 替换为实际上传 API 地址
                    listType="picture-card"
                    fileList={fileList}
                    onChange={onChange}
                    beforeUpload={beforeUpload}
                    maxCount={1} // 限制只能上传一个文件
                    onPreview={(file) => {
                      // 预览上传的图片
                      window.open(file.url);
                    }}
                    // 自定义上传请求，携带 biz 信息和 token
                    customRequest={(options) => {
                      const { onError, file } = options;

                      // 创建 FormData 实例
                      const formData = new FormData();
                      formData.append("file", file); // 添加文件
                      formData.append("biz", "room_cover"); // 添加 biz 信息
                      // 发送上传请求
                      fetch("http://localhost:8102/api/file/upload", {
                        method: "POST",
                        headers: {
                          // 你可以在这里添加其他自定义头部，但 Cookie 会自动发送
                          // 例如：
                          Cookie: getSessionInfo(),
                        },
                        body: formData, // 通过 FormData 发送文件和数据
                        credentials: "include", // 使请求携带 Cookies（用于跨域请求）
                      })
                        .then((response) => response.json()) // 处理响应
                        .then((data) => {
                          // 上传成功
                          // 上传成功后，通过 dispatch 来更新 loginUser
                          const newAvatarUrl = data.data;
                          setFileList([
                            {
                              uid: "-1", // 每个文件必须有唯一的 uid
                              name: "room_cover", // 文件名称
                              status: "done", // 状态为 done，表示上传完成
                              url: newAvatarUrl, // 用户的头像 URL
                            },
                          ]);
                        })
                        .catch((error) => {
                          // 上传失败
                          onError && onError(error);
                        });
                    }}
                  >
                    {fileList.length < 1 && (
                      <div>
                        <UploadOutlined />
                        <p>点击上传</p>
                      </div>
                    )}
                  </Upload>
                </ImgCrop>
              </Form.Item>
              <Form.Item className={"flex justify-end"}>
                <Button
                    color="primary"
                    variant="solid"
                    style={{ borderRadius: 3 }}
                    htmlType="submit"
                    onClick={() => {
                      message.success("添加房间成功！");
                      //navigate("/home");
                    }}
                >
                  添加房间
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default AddRoom;
